<?php

class RCMS_Object_PayPal_PayPal {

    private $_apiUsername = '';
    private $_apiPassword = '';
    private $_apiSignature = '';
    private $_model = null;

    const API_ENDPOINT = 'https://api-3t.paypal.com/nvp';
    const API_VERSOIN = '56.0';
    

    public function  __construct()
    {
        $this->_model = new RCMS_Object_PayPal_PayPalModel();
        $settings = unserialize($this->_model->selectSettingsPayPal());
        if (is_array($settings) && !empty ($settings)) {
            if (isset ($settings['signature'])) {
                $this->_apiSignature = trim($settings['signature']);
            }
            if (isset ($settings['user'])) {
                $this->_apiUsername = trim($settings['user']);
            }
            if (isset ($settings['password'])) {
                $this->_apiPassword = trim($settings['password']);
            }
        }
    }

	private function _hashCall($methodName, $nvpStr)
    {
        $coreData = array (
            'METHOD'        =>  $methodName,
            'VERSION'       =>  self::API_VERSOIN,
            'PWD'           =>  $this->_apiPassword,
            'USER'          =>  $this->_apiUsername,
            'SIGNATURE'     =>  $this->_apiSignature
        );
        $nvpRequest = http_build_query($coreData) . $nvpStr;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, self::API_ENDPOINT);
		curl_setopt($ch, CURLOPT_VERBOSE, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpRequest);
		$response = curl_exec($ch);
		curl_close($ch);
        return $this->_parseResponse($response);
	}

    private function _parseResponse($response)
    {
        $data = array();
        $tmp  = explode('&', $response);
        foreach ($tmp as $item) {
            $val = explode('=', $item);
            if (isset($val[0]) && isset($val[1])) {
                $data[$val[0]] = urldecode($val[1]);
            }
        }
        return $data;
    }

    public function createDoDirectPayment(array $data)
    {
        $stringRequest = '&'.http_build_query($data);
        return $this->_hashCall('DoDirectPayment', $stringRequest);
    }

    public function getTransactionDetails($transactionId)
    {
        $stringRequest = '&TRANSACTIONID='.urlencode($transactionId);
        return $this->_hashCall('GetTransactionDetails', $stringRequest);
    }
}
